package com.china08.yxyapi.api.manage.tec.teaching.homework.uploadques;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.SystemConstant;
import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.yxy.YxyQuesKnow;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.res.AllTemplate;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Answer;
import com.china08.yxyapi.entity.mg.res.AllTemplate.Branch;
import com.china08.yxyapi.model.question.QuestionUploadKnowModel;
import com.china08.yxyapi.repository.db.YxyQuesKnowRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.ElasticQuesService;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class homeworkQuesGetController extends YxyApiBaseController {

    @Autowired
    private ElasticQuesService elasticQuesService;

    @Autowired
    private YxyQuesKnowRepository yxyQuesKnowRepository;

    @ApiOperation(value = "获取试题详情")
    @RequestMapping(value = "/api_yw/manage/tec/homework/question/get/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel process(HttpServletRequest request, HttpServletResponse response,
            @PathVariable(value = "id") String id) throws JsonParseException, JsonMappingException, IOException {
        String userId = getProfile(request, response).getId();
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = elasticQuesService.findByEsQuesId(id);
        Assert.notNull(elasticYxyYxyQuesResource, "试题找不到了");
        Assert.isTrue(StringUtils.equals(userId, elasticYxyYxyQuesResource.getCreatedBy()), "这不是您上传的试题");
        String questionType = elasticYxyYxyQuesResource.getQuestionType();
        RespModel model = new RespModel();
        if (StringUtils.equalsIgnoreCase("1", questionType)) {
            model = getModelXuanze(elasticYxyYxyQuesResource);
        } else if (StringUtils.equalsIgnoreCase("2", questionType)) {
            model = getModelTiankong(elasticYxyYxyQuesResource);
        } else if (StringUtils.equalsIgnoreCase("8", questionType)) {
            model = getModelXuanze(elasticYxyYxyQuesResource);
        } else {
            model = getModelJieDa(elasticYxyYxyQuesResource);
        }
        List<QuestionUploadKnowModel> knowModels = new ArrayList<QuestionUploadKnowModel>();
        List<Integer> knowList = elasticYxyYxyQuesResource.getKnowledgeIds();
        if (knowList != null && knowList.size() > 0) {
            List<YxyQuesKnow> knows = yxyQuesKnowRepository.findByIdIn(knowList);
            for (YxyQuesKnow yxyQuesKnow : knows) {
                QuestionUploadKnowModel knowModel = new QuestionUploadKnowModel();
                knowModel.id = yxyQuesKnow.getId();
                knowModel.name = yxyQuesKnow.getName();
                knowModels.add(knowModel);
            }
        }
        model.knowModels = knowModels;
        model.questionType = elasticYxyYxyQuesResource.getQuestionType();
        model.difficultyLevel = elasticYxyYxyQuesResource.getDifficultyLevel();
        model.srcType = elasticYxyYxyQuesResource.getSrcType();
        model.phase = elasticYxyYxyQuesResource.getPhase();
        model.subject = elasticYxyYxyQuesResource.getSubject();
        return model;
    }

    private RespModel getModelJieDa(ElasticYxyYxyQuesResource elasticYxyYxyQuesResource)
            throws JsonParseException, JsonMappingException, IOException {
        RespModel model = new RespModel();
        JieDaModel jieDaModel = new JieDaModel();
        AllTemplate template = (AllTemplate) elasticYxyYxyQuesResource.getQuesBody();
        jieDaModel.tigan = template.sub.stem.body;
        jieDaModel.fenxi = template.sub.analysis.body;
        // 答案
        List<Answer> answers = template.sub.answer;
        List<String> stringAnswer = new ArrayList<String>();
        for (Answer answer : answers) {
            stringAnswer.add(answer.getBody());
        }
        jieDaModel.answer = StringUtils.join(stringAnswer, ",");
        model.jieDaModel = jieDaModel;
        return model;
    }

    private RespModel getModelTiankong(ElasticYxyYxyQuesResource elasticYxyYxyQuesResource)
            throws JsonParseException, JsonMappingException, IOException {
        RespModel model = new RespModel();
        TianKongModel tianKongModel = new TianKongModel();
        AllTemplate template = (AllTemplate) elasticYxyYxyQuesResource.getQuesBody();
        String tigan = template.sub.stem.body;
        List<Answer> answers = template.sub.answer;
        int i = 0;
        int answersIndex = -1;
        System.out.println(tigan);
        boolean flag = true;
        while (flag) {
            int index = tigan.indexOf(SystemConstant.TIANKONG_REGEX_XIAHUAXIAN);
            if (index > -1) {
                if (i <= answers.size()) {
                    int indexOf = tigan.indexOf(SystemConstant.TIANKONG_REGEX_XIAHUAXIAN, answersIndex);
                    // ##
                    System.out.println(indexOf);
                    tigan = tigan.substring(0, indexOf) + SystemConstant.TIANKONG_REGEX + answers.get(i).body
                            + SystemConstant.TIANKONG_REGEX
                            + tigan.substring(indexOf + SystemConstant.TIANKONG_REGEX_XIAHUAXIAN.length());
                    // ##
                    answersIndex = indexOf;
                    i++;
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
            System.out.println(tigan);
        }
        tianKongModel.tigan = tigan;
        tianKongModel.fenxi = template.sub.analysis.body;
        model.tianKongModel = tianKongModel;
        return model;
    }

    private RespModel getModelXuanze(ElasticYxyYxyQuesResource elasticYxyYxyQuesResource)
            throws JsonParseException, JsonMappingException, IOException {
        RespModel model = new RespModel();
        XuanzeModel xuanzeModel = new XuanzeModel();
        AllTemplate template = (AllTemplate) elasticYxyYxyQuesResource.getQuesBody();
        xuanzeModel.tigan = template.sub.stem.body;
        xuanzeModel.fenxi = template.sub.analysis.body;
        // 答案
        List<Answer> answers = template.sub.answer;
        List<String> stringAnswer = new ArrayList<String>();
        for (Answer answer : answers) {
            String strAnswer = answer.getBody();
            String[] strings = strAnswer.split(",");
            for (String string : strings) {
                stringAnswer.add(string);
            }
        }

        List<Branch> branchs = template.sub.branch;
        List<XuanZeChoose> chooses = new ArrayList<homeworkQuesGetController.XuanZeChoose>();
        for (Branch branch : branchs) {
            XuanZeChoose choose = new XuanZeChoose();
            choose.no = branch.no;
            choose.answer = stringAnswer.contains(choose.no);
            choose.choose = branch.body;
            chooses.add(choose);
        }
        xuanzeModel.chooses = chooses;
        model.xuanzeModel = xuanzeModel;
        return model;
    }

    protected static class XuanZeChoose {
        public String no;
        public String choose;
        public boolean answer;
    }

    protected static class XuanzeModel {
        public String tigan;
        public List<XuanZeChoose> chooses;
        public String fenxi;
    }

    protected static class TianKongModel {
        public String tigan;
        public String fenxi;
    }

    protected static class JieDaModel {
        public String tigan;
        public String answer;
        public String fenxi;
    }

    protected static class RespModel {
        public String questionType;
        public String difficultyLevel;
        public String srcType;
        public String phase;
        public String subject;
        public List<QuestionUploadKnowModel> knowModels;
        public XuanzeModel xuanzeModel;
        public TianKongModel tianKongModel;
        public JieDaModel jieDaModel;
    }

}
